﻿Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports System
Imports System.Security.Claims
Imports System.Web

Partial Public Class RegisterExternalLogin
  Inherits System.Web.UI.Page
    Protected Property ProviderName() As String
        Get
            Return If(DirectCast(ViewState("ProviderName"), String), [String].Empty)
        End Get
        Private Set(value As String)
            ViewState("ProviderName") = value
        End Set
    End Property

    Protected Property ProviderAccountKey() As String
        Get
            Return If(DirectCast(ViewState("ProviderAccountKey"), String), [String].Empty)
        End Get
        Private Set(value As String)
            ViewState("ProviderAccountKey") = value
        End Set
    End Property

    Protected Sub Page_Load() Handles Me.Load
        ' Process the result from an auth provider in the request
        ProviderName = OpenAuthProviders.GetProviderNameFromRequest(Request)
        If [String].IsNullOrEmpty(ProviderName) Then
            Response.Redirect("~/Account/Login")
        End If
        If Not IsPostBack Then
            Dim manager = New AuthenticationIdentityManager(New IdentityStore()).Authentication
            Dim auth = Context.GetOwinContext().Authentication
            Dim id As ClaimsIdentity = manager.GetExternalIdentity(auth)
            Dim result As IdentityResult = manager.SignInExternalIdentity(auth, id)
            If result.Success Then
                OpenAuthProviders.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
            ElseIf User.Identity.IsAuthenticated Then
                result = manager.LinkExternalIdentity(id, User.Identity.GetUserId())
                If result.Success Then
                    OpenAuthProviders.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
                Else
                    AddErrors(result)
                    Return
                End If
            Else
                userName.Text = id.Name
            End If
        End If
    End Sub

    Protected Sub LogIn_Click(sender As Object, e As EventArgs)
        CreateAndLoginUser()
    End Sub

    Private Sub CreateAndLoginUser()
        If Not IsValid Then
            Return
        End If
        Dim user = New User(userName.Text)
        Dim manager = New AuthenticationIdentityManager(New IdentityStore()).Authentication
        Dim result As IdentityResult = manager.CreateAndSignInExternalUser(Context.GetOwinContext().Authentication, user)
        If result.Success Then
            OpenAuthProviders.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
        Else
            AddErrors(result)
            Return
        End If
    End Sub

    Private Sub AddErrors(result As IdentityResult)
      For Each [error] As String In result.Errors
          ModelState.AddModelError("", [error])
      Next
    End Sub
End Class

